package com.tduck.cloud.storage.cloud;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import com.tduck.cloud.storage.exception.StorageException;

import cn.hutool.core.io.FileUtil;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class MinioStorageService extends OssStorageService {

	private MinioClient client;
	
	public OssStorageConfig config;
	
	public MinioStorageService(OssStorageConfig config) {
		this.config=config;
		try {
			 client = new MinioClient(config.getDomain(),config.getAccessKeyId(),config.getAccessKeySecret());
			if(client.bucketExists(config.getBucketName())) {
				log.info("已创建桶");
			}else {
				client.makeBucket(config.getBucketName());
				log.info("成功创建桶");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
	
	@Override
	public String upload(InputStream inputStream, String path) {
		try {
			Map<String, String> headers = new HashMap<String, String>();
			headers.put("Content-Type", FileUtil.extName(path));
			PutObjectOptions options = new PutObjectOptions(inputStream.available(), -1);
			options.setHeaders(headers);
			client.putObject(config.getBucketName(), path, inputStream, options);
		} catch (Exception e) {
			throw new StorageException("上传文件失败，请核对Minio配置信息", e);
		}
	   return config.getDomain()+"/"+config.getBucketName()+"/"+ path;
	}

	@Override
	public String upload(byte[] data, String path) {
		InputStream inputStream = new ByteArrayInputStream(data);
		try {
			Map<String, String> headers = new HashMap<String, String>();
			headers.put("Content-Type",FileUtil.extName(path));
			PutObjectOptions options = new PutObjectOptions(inputStream.available(), -1);
			options.setHeaders(headers);
			client.putObject(config.getBucketName(), path, inputStream, options);
		} catch (Exception e) {
			throw new StorageException("上传文件失败，请核对Minio配置信息", e);
		}
		return config.getDomain()+"/"+config.getBucketName()+"/"+ path;
	}

	@Override
	public void delete(String path) {
		try {
			client.deleteBucketLifeCycle(config.getBucketName()+"/"+ path);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
